from copy import deepcopy
from threading import Lock

from loguru import logger

from sqlalchemy.orm import Session

from common.db.tables import taobao as taobao_table
from common.schema import taobao as taobao_schema


def get_order(db: Session, android_ip: str) -> taobao_table.Order:
    data = db.query(taobao_table.Order).filter(taobao_table.Order.android_ip == android_ip).first()
    return deepcopy(data)


def get_order_by_user(db: Session, user: str) -> taobao_table.Order:
    data = db.query(taobao_table.Order).filter(taobao_table.Order.user == user).first()
    return deepcopy(data)


def get_orders(db: Session, limit: int = 100) -> [taobao_table.Order]:
    data = db.query(taobao_table.Order).limit(limit).all()
    return deepcopy(data)


def update_order(db: Session, android_ip: str, update_value: dict) -> taobao_table.Order:
    db_order = db.query(taobao_table.Order).filter(taobao_table.Order.android_ip == android_ip).first()
    for key, value in update_value.items():
        setattr(db_order, key, value)
    db.add(db_order)
    db.commit()
    db.refresh(db_order)
    return deepcopy(db_order)


def create_order(db: Session, order: taobao_schema.TaoBaoOrderTask) -> taobao_table.Order:
    db_order = taobao_table.Order(**order.dict())
    db.add(db_order)
    db.commit()
    db.refresh(db_order)
    return deepcopy(db_order)


def delete_order(db: Session, android_ip: str):
    orders = db.query(taobao_table.Order).filter(taobao_table.Order.android_ip == android_ip).all()
    for order in orders:
        db.delete(order)
        logger.info('delete db android_ip={} order {}'.format(order, order.to_dict()))
    db.commit()
